package com.hunantv.mglive.ui.discovery.publisher.pic;

import android.content.Context;
import android.graphics.Bitmap;

import com.hunantv.mglive.ui.discovery.publisher.pic.LruImageCache;

/**
 * @author maxxiang
 * 唯一的为UI提供所有需要图片显示的接口

 * 使用方法：
1. 用NetworkImageView代替ImageView.
2.加载图片示例代码:
NetworkImageView image = (NetworkImageView)v.findViewById(R.id.Image);
image.setImageUrl(url, ImageCacheManager.getInstance().getImageLoader());
 */
public class ImageCacheManager {

	private static ImageCacheManager mInstance;

	/**
	 * Memory Cache Size,  10M is the default value
	 */
	private int lMemoryCacheSize = 10 * 1024 * 1024;

	/**
	 * Image cache implementation
	 */
	private LruImageCache mImageCache;

	/**
	 * @return
	 * 		instance of the cache manager
	 */
	public static ImageCacheManager getInstance(){
		if(mInstance == null)
			mInstance = new ImageCacheManager();

		return mInstance;
	}

	public void init(Context context){
		init(context, lMemoryCacheSize);
	}

	public void init(Context context, int cacheSize){
		mImageCache = new LruImageCache(cacheSize);
	}

	public Bitmap getBitmap(String url) {
		try {
			return mImageCache.getBitmap(createKey(url));
		} catch (NullPointerException e) {
			throw new IllegalStateException("Image Cache Not initialized");
		}
	}

	public void putBitmap(String url, Bitmap bitmap) {
		try {
			mImageCache.putBitmap(createKey(url), bitmap);
		} catch (NullPointerException e) {
			throw new IllegalStateException("Image Cache Not initialized");
		}
	}



	/**
	 * Creates a unique cache key based on a url value
	 * @param url
	 * 		url to be used in key creation
	 * @return
	 * 		cache key value
	 */
	private String createKey(String url){
		return String.valueOf(url.hashCode());
	}

	public LruImageCache getImageCache(){
		return mImageCache;
	}
}
